%MCGH2: Matlab toolbox for analysising cDNA microarrray-based CGH experiemnts
%June. 2004. Tumor Biology Department, The norwegian radium hospital, 
%Author: junbai wang
%
global numofrun xtick_labels xtick_locations chrom_rang PlotMeanCenter F2  runcode numberofCenter fileform inter_value cloneName ChrNo iserrorBar p_1 p1 p0 m1 m0 m_1 s_1 s1 s0 isAmpPlot find_cloneString outdata varnames findClone_fig sleng F1
global stdBackIn maxStd_rep ismcgh2

warning off;
set(0,'ShowHiddenHandles','off')
if ( ~exist('GUIF1') ) 
    close all hidden;
    clear all;
    %close all hidden;
   GUIF1=0;
   find_cloneString='';
	%Default input values
   %Initial parameter
    m1=1.5;
    s1=0.2;
    p1=0.1;
    m0=0;
    s0=0.1;
    p0=0.8;
    m_1=-1.5;
    s_1=0.2;
    p_1=0.1;
    runcode=0;
    mcgh_plotter;
    F1=1;
    F2=2;
    isAmpPlot=3;
    numofrun=0;
    xtick_labels={};
    PlotMeanCenter=0;
    normtype=1;
    %isexport=1;
     waitn=6;
    numberofCenter=2;
    fileform=2;
    inter_value=3;
    iserrorBar=2;
    isloaded=1;
    maxStd_rep=2;
    stdBackIn=3;
    ismcgh2=1;
    %define menue
     % h =0;
end;

if GUIF1==0
figure(F2); %   control window
set(F2,'Color',[0.8 1 1], ...
    'units','normalized', ... 
    'Position',[0.1 0.07 0.45 0.50], ...
   	'Tag','F2',...
    'NumberTitle','off',...
    'Name','M-CGH2');
	%'DoubleBuffer','on',...
    
frmPos=[1 50 520 310];
vvv=uicontrol(...
   'Style','frame', ...
   'Units','pixels', ...
   'Position',frmPos, ...
   'BackgroundColor',[0.5 0.5 0.5]);

%define menu
if ~exist('fmenu')
    fmenu=uimenu('Parent',F2,'Label','M-CGH2 find clone'); 
    uimenu(fmenu,'Label','Find clone','Callback','mcgh_findClone'); 
end

if ~exist('pmenu')
    pmenu=uimenu('Parent',F2,'Label','M-CGH2 property'); 
    uimenu(pmenu,'Label','MCGH2 property','Callback','mcgh_properties'); 
end

if ~exist('hmenu')       
    hmenu=uimenu('Label','M-CGH2 Help'); 
    uimenu(hmenu,'Label','M-CGH2 Help','Callback','mcgh_help'); 
end
    
%open file1
openBut1=uicontrol('style','push','string','Open MM-CGH export File',...
	'position',[3 470 135 20], ...
	'callback', [' [file1, path1]=uigetfile({''*.*'', ''All Files (*.*)''});numofrun=0;p1=0.1;p_1=0.1;p0=0.8;m1=1;m0=0;m_1=-1;s1=0.2;s_1=0.2;s0=0.1;mcgh2;'],...
	'Interruptible','on');
	if exist('file1')
 	file_name1=uicontrol('Style','text','HorizontalAlignment','left',...
 	'Position',[150 470 180 20],...
 	'String', file1); 
	end


%plot normalized ratio button
NPlot=uicontrol('style','push','string','Genome plot with mean centered Ratio',...
   'position',[190 370 190 20 ], ...
   'callback', ['runcode=0;eval(NPStr1);' ], ...
   'Interruptible','on');

%plot each chromosome button
ChrPlot=uicontrol('style','popupmenu',...
   'position',[410 370 100 20 ], ...
   'String','Chr plot 1|Chr plot 2|Chr plot 3|Chr plot4|Chr plot 5|Chr plot 6|Chr plot 7|Chr plot 8|Chr plot 9|Chr plot 10|Chr plot 11|Chr plot 12|Chr plot 13|Chr plot 14|Chr plot 15|Chr plot 16|Chr plot 17|Chr plot 18|Chr plot 19|Chr plot 20|Chr plot 21|Chr plot 22|Chr plot X|Chr plot Y|plot OneQ|Plot OncoBAC|Plot Extra|Plot Chr 1-Y',...
   'callback', ['runcode=0;ChrNo=get(ChrPlot,''Value'');eval(ChrPStr1);' ]);


ReFresh=uicontrol('style','push','string','Refesh figure of raw ratio plot',...
   'position',[3 370 175 20 ], ...
   'callback', ['runcode=0;eval(str1);' ], ...
   'Interruptible','on');


loadtype=uicontrol('Style','popupmenu',...
        'Position',[ 90 27 120 20],...   
        'String', 'Load new input data|Use last loaded data', ... %
        'Callback',['isloaded=get(loadtype,''Value'');']);


%
%clone2www	button
%
Bclone=uicontrol('style','push','string','Clone2Web',...
   'position',[140 5 70 20],...
    'callback', [ 'mcgh_clone2web(cloneName)'], ...
   'Interruptible','on');



%%normalization choice
%ntype=uicontrol('Style','popupmenu',...
%        'Position',[ 3 400 180 20],...   
%        'String', 'Simple normalization|Intensity dependent normalization|Sub-array position normalization', ... %type1=1, type2=2
%        'Callback',['numofrun=0;normtype=get(ntype,''Value'');p1=0.1;p_1=0.1;p0=0.8;m1=1;m0=0;m_1=-1;s1=0.2;s_1=0.2;s0=0.1;']);


%file type choice
ftype=uicontrol('Style','popupmenu',...
        'Position',[ 350 470 120 20],...   
        'String', 'QuantArray format|GenePix format', ... %type1=1, type2=2
        'Callback',['fileform=get(ftype,''Value'');numofrun=0;p1=0.1;p_1=0.1;p0=0.8;m1=1;m0=0;m_1=-1;s1=0.2;s_1=0.2;s0=0.1;']);
    
    
%%export choice
iexport=uicontrol('Style','push','string','Export data',...
        'Position',[60 5 70 20 ],...   
        'Callback',...
        ['corrected_ratio=final_ratio1(IB)''-m0;corrected_ratio=reshape(corrected_ratio,length(corrected_ratio),1);old_corrected_ratio=reshape(old_corrected_ratio,length(old_corrected_ratio),1);old_corrected_ratio(n_IB,:)=corrected_ratio(n_IA,:);mcgh_export(old_Chor,old_outdata,casenames,old_names,[filename1,''MCGH2''],old_corrected_ratio,sorteddata);']);

     %   'Callback',['corrected_ratio=final_ratio1(IB)''-m0;old_corrected_ratio(n_IB,:)=corrected_ratio(n_IA,:);mcgh_export(outdata,casenames,varnames,filename1,corrected_ratio);']);

%%number of centers choice
numCenter=uicontrol('Style','popupmenu',...
        'Position',[ 190 400 110 20],...   
        'String', '2 c-mean centers |3 c-mean centers', ...        
        'Callback',['numberofCenter=get(numCenter,''Value'');']);

%%error bar plot
ierrorBar=uicontrol('Style','popupmenu',...
        'Position',[ 430 400 80 20],...   
        'String', 'Error bar|No error bar', ...        
        'Callback',['iserrorBar=get(ierrorBar,''Value'');']);

%%amplify boundary plot
iampBar=uicontrol('Style','popupmenu',...
                   'position',[305 400 125 20],...
                    'String','WaveLet-Amplicon boundaries|KNN-Amplicon boundaries|Non amplicon boundaries',...
                    'Callback',['isAmpPlot=get(iampBar,''Value'');']);
%run button
Brun=uicontrol('style','push','string','Run program',...
   'position',[3 27 70 20 ], ...
   'callback', ['runcode=1;mcgh2;' ], ...
   'Interruptible','on');

heighth=46+9*23+3;
%
%  Exit Button ; exit the program
%
ExitBut=uicontrol('style','pushbutton',...
                 'string','EXIT','position', [3 5 50 20],...
                 'callback','close all hidden;clear all;');


nstring={'m1','s1','p1','m0','s0','p0','m_1','s_1','p_1'};   %   names of all parameters in one
nstringNote={'Mean of Gain','STD of Gain','Propotion of Gain','Mean of Normal','STD of Normal','Propotion of Normal',...
        'Mean of Loss', 'STD of Loss','Propotion of Loss'};
sleng=200; ys=23;     
%   used for sizes of controls
%Labels min, max
uicontrol('style','text',...
                 'string','Min','position', [3 340 25 20],...
                 'BackgroundColor',[1 1 1]);
uicontrol('style','text',...
                 'string','Max','position', [sleng+30 340 25 20],...
                 'BackgroundColor',[1 1 1]);
             

%define 9 parameters to fit 3 centered normal Gaussian distribution 
slider_idx_M=1:3:9;
slider_idx_S=2:3:9;
slider_idx_P=3:3:9;

slider_min_P=0;
slider_max_P=1;
    
slider_min_S=-2;
slider_max_S=2;
  
slider_min_M=-4;
slider_max_M=4;
  
for ksl=1:9
 ns=char(nstring{ksl});
 nsN=char(nstringNote{ksl});
 nsNote=strcat(nsN,', ',ns,' ');
  nf(ksl)=uicontrol('style','text','string',nsNote,...
        'position',[sleng+60 ys+ksl*33  115 20]);
  

  CALLBACK=[ ns '=get(slf(' num2str(ksl) '),''value'');eval(str1);numofrun=numofrun+1;' ];
  %% 
  %%  Callback uses str1 constructed by plotter.m
  %%  Change the range of a,b,c,d,e,f  
  if ismember(ksl,slider_idx_P) 
    
    uicontrol('style','text','string',num2str(slider_min_P),'position',[3 ys+ksl*33  25 20],...
        'BackgroundColor',[1 1 1]);
    uicontrol('style','text','string',num2str(slider_max_P),'position',[sleng+30 ys+ksl*33  25 20],...
          'BackgroundColor',[1 1 1]);
  
    slf(ksl)=uicontrol('style','slider',...
       'min',slider_min_P,'max',slider_max_P,'SliderStep',[0.01 0.1],...
       'position',[30  ys+ksl*33 sleng 20],...
    'value',0.01,    ...
    'callback',CALLBACK);
  elseif  ismember(ksl,slider_idx_S) 
    uicontrol('style','text','string',num2str(slider_min_S),'position',[3 ys+ksl*33  25 20],...
        'BackgroundColor',[1 1 1]);
    uicontrol('style','text','string',num2str(slider_max_S),'position',[sleng+30 ys+ksl*33  25 20],...
          'BackgroundColor',[1 1 1]);
  
    slf(ksl)=uicontrol('style','slider',...
       'min',slider_min_S,'max',slider_max_S,'SliderStep',[0.0025 0.025],...
       'position',[30  ys+ksl*33 sleng 20],...
    'value',0.01,    ...
    'callback',CALLBACK);
  elseif ismember(ksl,slider_idx_M) 
   uicontrol('style','text','string',num2str(slider_min_M),'position',[3 ys+ksl*33  25 20],...
        'BackgroundColor',[1 1 1]);
    uicontrol('style','text','string',num2str(slider_max_M),'position',[sleng+30 ys+ksl*33  25 20],...
          'BackgroundColor',[1 1 1]);
    slf(ksl)=uicontrol('style','slider',...
       'min',slider_min_M,'max',slider_max_M,'SliderStep',[0.0025 0.025],...
       'position',[30  ys+ksl*33 sleng 20],...
    'value',0.01,    ...
    'callback',CALLBACK);
  end
end                    
%% end Sliders defined
%'Units','normalized'
%[.65 .85  .4 0.05]
%    'FontUnits', 'Normalized',...
%define intervalue for the window size
htxt_window_size=uicontrol('Parent',F2,...
		    'Style', 'text', ...
		    'Position',[350 440 120 20] ,...
		    'Backg', [1 1 1], ...
		    'Foreg', [0 0 0], ...
		    'String','Average window size', ...
		    'FontSize',1, ...
		    'FontWeight',  'normal', ...
		    'HorizontalAlignment', 'left', ...
		    'Tag', 'average_widdow_size');

window_size_field=uicontrol('Style','edit','Position', [460 440 50 20],...
         'BackgroundColor','white',...
         'CallBack',['inter_value=str2num(get(window_size_field,''String''));']);
   %[.91 .85  .08 0.05],...             
   % 'Units', 'normalized', ...
    
if runcode==1
 marray_debuge(['','\n']);
 marray_debuge(['','\n']);
 h = waitbar(0,'Please wait...');
 waitn=6;
 waiti=1;
 waitbar(waiti/waitn,h);
%iinitila    
numofrun=0;
xtick_labels={};
xtick_locations=[];
chrom_rang=[];

warning off;
if ~isempty(path1) & ~isempty(file1)
 filename1=[path1,file1];
 disp(['Load MM-CGH export file: ',filename1]);
end

if isloaded==1
     marray_debuge(['Loading : ',filename1]);
    data1=[];
    inputdata1=[];
    inputdata1=marray_testload_marray(filename1);
    marray_debuge('MM-CGH export data');
    
else
     marray_debuge('Use last loaded data!');
end

waitbar(2/waitn,h);

%start to plot figures
%%start to modify
%[cond1 filtered_redsub1 filtered_greensub1]=lenod_filter(inputdata1);
%size(find(cond1~=0))
%ref1or2=1;
%figno=11;
%alpha=0;
%ch1_int=1;
%ch2_int=1;
%ch1_intUser=0;
%ch2_intUser=0;
%[cond, newdata,newdata_intensity,q_com,q_com1,q_com2,idxq_com,rep_flag1,rep_flag2,minIntensity_ch1,minIntensity_ch2]...
%    =mcgh_SfilterBad(inputdata1,ref1or2,normtype,figno,alpha,ch1_int,ch2_int,ch1_intUser,ch2_intUser);
% waitbar(3/waitn,h);
%filtered_ratio=newdata(:,2);
%idx_filtered=find(filtered_ratio~=0);

%norm_ratio1=filtered_ratio(idx_filtered);
%filtered_name1=inputdata1.Name(idx_filtered,:);
%end modify


%len=length(norm_ratio1);
%f_name1=mcgh_BacName(len,filtered_name1);
%log2_norm1=log2(norm_ratio1);
%marray_debuge('Log2 transfer normalized ratio');
%[final_name1 , final_ratio1, final_std1,final_numofdup1]=mcgh_mean(f_name1,log2_norm1);

%Find no missing spots
nomiss_idx=find(str2num(strvcat(inputdata1.Number_of_repeated_spots))~=0);
temp_final_name1=mcgh_BacName(length(inputdata1.CloneID),inputdata1.CloneID);
sorteddata.BAC_PAC=temp_final_name1;
final_name1=temp_final_name1(nomiss_idx);
temp_final_ratio1=str2num(strvcat(inputdata1.Normalized_ratio));
final_ratio1=temp_final_ratio1(nomiss_idx);
temp_final_std1=str2num(strvcat(inputdata1.STD_of_ratio));
final_std1=temp_final_std1(nomiss_idx);
temp_final_numofdup1=str2num(strvcat(inputdata1.Number_of_repeated_spots));
final_numofdup1=temp_final_numofdup1(nomiss_idx);

sorteddata.Order_Number=inputdata1.Genome_position;
sorteddata.position=inputdata1.All_genome_position;
sorteddata.Chorsmor=inputdata1.Chromosome;

%waitbar(4/waitn,h);
%marray_debuge('Loading clone locations ..')
%[sorteddata,colname]=marray_testload_marray(filename);
%A=strrep(lower(deblank(sorteddata.BAC_PAC)),'_','');
%B=strrep(lower(deblank(final_name1)),'_','');
A=strrep(lower(deblank(temp_final_name1)),'_','');
B=strrep(lower(deblank(final_name1)),'_','');
[C IA IB]=intersect(A,B);
eval(str2);
%marray_debuge(['The number of total clones is ', num2str(length(IB))]);
runcode=0;
numofrun=numofrun+1;

varnames=(A(IA));
Chor=((sorteddata.Chorsmor(IA)));
Genom_position=str2num(strvcat(sorteddata.Order_Number(IA)));

lnIA=length((IA));
IA=reshape(IA,lnIA,1);
corrected_ratio=final_ratio1(IB)'-m0;

outdata=[reshape(final_ratio1(IB),length(final_ratio1(IB)),1),...
         reshape(corrected_ratio,length(corrected_ratio),1),...
         reshape(final_std1(IB),length(final_std1(IB)),1),...
         reshape(final_numofdup1(IB),length(final_numofdup1(IB)),1),...
         reshape(Genom_position,length(Genom_position),1) ];


%added jbw
%original all names
clear old_outdata old_corrected_ratio old_names

len=size(inputdata1.CloneID,1);
old_names=unique(mcgh_BacName(len,inputdata1.CloneID));
[old_r old_c]=size(old_names);

old_r=max([old_r,old_c]);
old_outdata=zeros(old_r,5); %GenPix data
old_corrected_ratio=zeros(old_r,1);
old_Chor=cellstr(repmat('NA',old_r,1));

new_names=varnames; %clone location data
[n_C,n_IA,n_IB]=intersect(strrep(lower(deblank(new_names)),'_',''),strrep(lower(deblank(old_names)),'_',''));
old_outdata(n_IB,:)=outdata(n_IA,:);
old_Chor(n_IB)=(Chor(n_IA));
corrected_ratio=reshape(corrected_ratio,length(corrected_ratio),1);
old_corrected_ratio(n_IB,:)=corrected_ratio(n_IA,:);
old_names=(lower(deblank(old_names)));
%end added


casenames=strvcat({'Normalized ratio' , 'Mean center corrected Ratio','STD of ratio', 'Number of repeated spots','Chromosome','Genome position','All genome position'});
 waitbar(5/waitn,h);
waitbar(6/waitn,h);
close(h);
end
 
%set(ntype,'Value',normtype);
set(numCenter,'Value',numberofCenter);
set(ftype,'Value',fileform);
set(ierrorBar,'Value',iserrorBar);
set(window_size_field,'String',num2str(inter_value));
set(iampBar,'Value',isAmpPlot);
set(loadtype,'Value',isloaded);

all_parameters=[m1 s1 p1 m0 s0 p0 m_1 s_1 p_1];
for ksl=1:9
     set(slf(ksl),'Value',all_parameters(ksl));
end

end %end all

